package com.shaoming.conf;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializerProvider;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;

import java.io.IOException;

/**
 * @author shaoming
 * @Date: 2021/3/8 14:51
 * @Description: springboot返回json数据对属性为null值的处理, 让其返回位空串""
 * 示例:
 * 没有配置类之前的json
 * User user = new User();
 * user.setId(1).setName("name").setJob("job");
 * {
 * "id": 1,
 * "name": "name",
 * "job": "job",
 * }
 * 项目添加配置类之后返回的json数据
 * {
 * "id": 1,
 * "status": "",
 * "name": "name",
 * "job": "job",
 * "salary": ""
 * }
 */
@Configuration
public class JacksonConfig {
    @Bean
    @Primary
    @ConditionalOnMissingBean(ObjectMapper.class)
    public ObjectMapper jacksonObjectMapper(Jackson2ObjectMapperBuilder builder) {
        ObjectMapper objectMapper = builder.createXmlMapper(false).build();
        objectMapper.getSerializerProvider().setNullValueSerializer(new JsonSerializer<Object>() {
            @Override
            public void serialize(Object o, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
                jsonGenerator.writeString("");
            }
        });
        return objectMapper;
    }
}
